package com.example.onlinefood.controller;

import com.example.onlinefood.domain.MenuItem;
import com.example.onlinefood.domain.Restaurant;
import com.example.onlinefood.mapper.MenuItemMapper;
import com.example.onlinefood.mapper.RestaurantMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/api/v1")
public class RestaurantController {
    private static final Logger logger = LoggerFactory.getLogger(RestaurantController.class);
    
    @Resource
    private RestaurantMapper restaurantMapper;
    @Resource
    private MenuItemMapper menuItemMapper;

    @GetMapping("/restaurants")
    public ResponseEntity<List<Restaurant>> list(
            @RequestParam(value = "q", required = false) String q,
            @RequestParam(value = "cuisine_type", required = false) String cuisineType,
            @RequestParam(value = "sort_by", required = false) String sortBy,
            @RequestParam(value = "order", required = false, defaultValue = "desc") String order) {
        logger.debug("Received request with parameters: q={}, cuisineType={}, sortBy={}, order={}", q, cuisineType, sortBy, order);
        
        try {
            if (q != null && q.trim().length() > 0) {
                logger.debug("Searching by name: {}", q.trim());
                List<Restaurant> result = restaurantMapper.searchByName(q.trim());
                // 尝试排序，但如果失败也不影响返回结果
                if (sortBy != null && ("rating".equals(sortBy) || "distance".equals(sortBy))) {
                    try {
                        sortRestaurants(result, sortBy, order);
                    } catch (Exception e) {
                        logger.warn("Sorting failed, returning unsorted results: {}", e.getMessage());
                    }
                }
                return ResponseEntity.ok(result);
            }
            if (cuisineType != null && cuisineType.trim().length() > 0) {
                logger.debug("Filtering by cuisine type: {}", cuisineType.trim());
                List<Restaurant> result = restaurantMapper.findByCuisineType(cuisineType.trim());
                // 尝试排序，但如果失败也不影响返回结果
                if (sortBy != null && ("rating".equals(sortBy) || "distance".equals(sortBy))) {
                    try {
                        sortRestaurants(result, sortBy, order);
                    } catch (Exception e) {
                        logger.warn("Sorting failed, returning unsorted results: {}", e.getMessage());
                    }
                }
                return ResponseEntity.ok(result);
            }
            
            logger.debug("Getting all restaurants");
            List<Restaurant> result = restaurantMapper.findAll();
            
            // 尝试排序，但如果失败也不影响返回结果
            if (sortBy != null && ("rating".equals(sortBy) || "distance".equals(sortBy))) {
                try {
                    logger.debug("Attempting to sort by {} in {} order", sortBy, order);
                    sortRestaurants(result, sortBy, order);
                } catch (Exception e) {
                    logger.warn("Sorting failed, returning unsorted results: {}", e.getMessage());
                }
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error processing request: {}", e.getMessage(), e);
            throw e;
        }
    }
    
    private void sortRestaurants(List<Restaurant> restaurants, String sortBy, String order) {
        if (restaurants == null || restaurants.isEmpty()) {
            logger.debug("No restaurants to sort");
            return;
        }
        
        logger.debug("Sorting {} restaurants by {} in {} order", restaurants.size(), sortBy, order);
        
        // 检查是否有非null的排序字段值
        boolean hasNonNullValues = false;
        if ("rating".equals(sortBy)) {
            hasNonNullValues = restaurants.stream().anyMatch(r -> r.getRating() != null);
        } else if ("distance".equals(sortBy)) {
            hasNonNullValues = restaurants.stream().anyMatch(r -> r.getDistance() != null);
        }
        
        if (!hasNonNullValues) {
            logger.debug("No non-null values found for sorting by {}", sortBy);
            return; // 没有可排序的值，直接返回
        }
        
        // 使用更健壮的比较器，处理null值
        Comparator<Restaurant> comparator;
        if ("rating".equals(sortBy)) {
            comparator = Comparator.comparing(
                r -> r.getRating() != null ? r.getRating() : Double.MIN_VALUE,
                Double::compare
            );
        } else if ("distance".equals(sortBy)) {
            comparator = Comparator.comparing(
                r -> r.getDistance() != null ? r.getDistance() : Double.MAX_VALUE,
                Double::compare
            );
        } else {
            logger.debug("Unsupported sort field: {}", sortBy);
            return; // 不支持的排序字段
        }
        
        // 根据order参数决定排序方向
        if ("desc".equalsIgnoreCase(order)) {
            comparator = comparator.reversed();
        }
        
        // 执行排序
        restaurants.sort(comparator);
        logger.debug("Sorting completed successfully");
    }

    @GetMapping("/restaurants/{id}")
    public ResponseEntity<Restaurant> detail(@PathVariable Integer id) {
        return ResponseEntity.ok(restaurantMapper.findById(id));
    }

    @GetMapping("/restaurants/{id}/menu")
    public ResponseEntity<List<MenuItem>> menu(@PathVariable Integer id,
                                               @RequestParam(value = "q", required = false) String q) {
        if (q != null && q.trim().length() > 0) {
            return ResponseEntity.ok(menuItemMapper.searchByRestaurantAndName(id, q.trim()));
        }
        return ResponseEntity.ok(menuItemMapper.findByRestaurantId(id));
    }
}


